package com.hzw.code.net

import com.hzw.code.net.bean.Http

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/4/15 14:07
 *
 * @Description:    RetrofitManager管理类
 *
 */

object HttpManager {

    private val list = mutableMapOf<String, Http>()

    fun addHttp(url: String, http: Http) {
        list[url] = http
    }

    fun removeHttp(url: String) {
        if (list.containsKey(url)) {
            list.remove(url)
        }
    }

    fun getHttp(url: String): Http? {
        if (list.containsKey(url)) {
            return list[url]
        }
        return null
    }

    fun <T> getApi(clazz: Class<*>): T {
        val baseUrl = HttpCreator.parseApiBaseUrl(clazz)

        var http = getHttp(baseUrl)
        if (http == null) {
            http = HttpCreator.create(clazz = clazz, headers = arrayOf())
            val t = http.retrofit!!.create(clazz)
            http.apiMap[clazz] = t!!
            return t as T
        }

        val api = http.apiMap[clazz]
        if (api == null) {
            HttpCreator.parseApiClass(clazz, http)
            val t = http.retrofit!!.create(clazz)
            http.apiMap[clazz] = t!!
            return t as T
        }
        return api as T
    }

}